import com.google.gson.Gson
import database.BottlePool
import database.UserMgr
import database.unixTime
import exceptions.*
import io.javalin.Javalin
import io.javalin.core.validation.ValidationException
import result.HttpResult
import tools.BotMgr
import java.text.SimpleDateFormat
import java.util.*

// 服务的入口
fun main() {
    val app = Javalin.create().start(12555)
    val gson = Gson()
    val dateFormat = SimpleDateFormat("YY-MM-dd HH:mm:ss")
    fun getCurTime(): String = dateFormat.format(Date(System.currentTimeMillis()))

    /**
     * 捞瓶子的 GET
     */
    app.get("/bottle/pick") {
        it.header("Content-Type", "text/html; charset=utf-8")
        try {
            val userId = it.queryParamAsClass<Long>("user_id").get()
            val groupId = it.queryParamAsClass<Long>("group_id").get()
            val botId = it.queryParamAsClass<Long>("bot_id").get()
            val user = UserMgr.initUser(userId = userId)
            val botName = BotMgr.getName(botId)
            println("[${getCurTime()}] User \"${userId}\" try to pick a bottle by Bot \"${botName}\".")
            val result = BottlePool.pick(user, groupId, botId)
            val jsonString = gson.toJson(result)
            it.result(jsonString)
        } catch (e: ValidationException) {
            it.result(
                gson.toJson(
                    HttpResult(
                        code = 400,
                        time = unixTime(),
                        message = "缺少必要的参数"
                    )
                )
            )
        } catch (e: ErrorBotIdException) {
            it.result(
                gson.toJson(
                    HttpResult(
                        code = e.code,
                        time = unixTime(),
                        message = "" + e.message
                    )
                )
            )
        } catch (e: Exception) {
            println(e.toString())
            it.result(
                gson.toJson(
                    HttpResult(
                        code = 500,
                        time = unixTime(),
                        message = "" + e.toString()
                    )
                )
            )
        }
    }

    /**
     * 丢瓶子的 POST
     */
    app.post("/bottle/send") {
        try {
            val userId = it.formParamAsClass<Long>("user_id").get()
            val groupId = it.formParamAsClass<Long>("group_id").get()
            val botId = it.formParamAsClass<Long>("bot_id").get()
            val content = it.formParamAsClass<String>("content").get()
            val user = UserMgr.initUser(userId = userId)
            val botName = BotMgr.getName(botId)
            println("[${getCurTime()}] User \"${userId}\" try to send a bottle by Bot \"${botName}\".")
            BottlePool.send(user, groupId, botId, content)
            it.status(200)
            it.result(gson.toJson(HttpResult(
                code = 200,
                time = unixTime(),
                message = "OK"
            )))
        } catch (e: BaseException) {
            it.status(200)
            it.result(gson.toJson(HttpResult(
                code = e.code,
                time = unixTime(),
                message = "" + e.message
            )))
        } catch (e: ValidationException) {
            println(e)
            it.status(200)
            it.result(gson.toJson(HttpResult(
                code = 500,
                time = unixTime(),
                message = "参数错误 " + e.message
            )))
        }  catch (e: Exception) {
            println(e)
            e.printStackTrace()
            it.status(500)
        }
    }

    /**
     * 查询排名的 GET
     */
    app.get("/bottle/rank") {
        it.header("Content-Type", "text/html; charset=utf-8")
        try {
            println("[${getCurTime()}] The RANK is queried.")
            it.result(
                gson.toJson(
                    HttpResult(
                        code = 200,
                        time = unixTime(),
                        message = BottlePool.rank()
                    )
                )
            )
        } catch (e: Exception) {
            println(e.toString())
            it.result(
                gson.toJson(
                    HttpResult(
                        code = 500,
                        time = unixTime(),
                        message = "" + e.toString()
                    )
                )
            )
        }
    }
}

